package com.mingqijia.gassafety.webserver.service.workorder.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gap.basic.exception.BizException;
import com.google.common.base.Joiner;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.MD5Util;
import com.mingqijia.gassafety.shared.dto.tcis.CancelBusiOrderDTO;
import com.mingqijia.gassafety.webserver.request.tcis.UnbindAlarmRequest;
import com.mingqijia.gassafety.webserver.service.impl.CompanyServiceImpl;
import com.mingqijia.gassafety.webserver.service.workorder.mbp.TcisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @program: gassafety
 * @description:
 * @author: Mr.Wang
 * @create: 2022-12-01 13:35
 **/
@Service
@Slf4j
public class TcisServiceImpl implements TcisService {

    @Value(value = "${gassafety.warnStrategy.openUrl}")
    public String targetUrl;

    @Value(value = "${gassafety.tcis.openAppId}")
    public String openId;

    @Value(value = "${gassafety.tcis.openAppSecret}")
    public String openSecret;

    @Autowired
    CompanyServiceImpl companyService;


    @Override
    public Map<String, Object> tcisRequest(Map<String, Object> jsonData, int type,
                                           String param, String consumerId) {
        String spId = ApplicationUtils.getWorkingSpId();
        String orgCode = companyService.getOrgCode(spId,consumerId);
        log.info("TcisService——tcisRequest,主要发送数据：{},type：{},param:{},consumerId:{}",
                JSONObject.toJSONString(jsonData), type, param,consumerId);
        if (StringUtils.isEmpty(param)) param = "";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", -1);
        resultMap.put("msg", "tcis请求失败");
        JSONObject jsonObject = null;
        Map<String, Object> params = new HashMap<>();
        if (jsonData != null) {
            params = jsonData;
        }
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            params.put("data", JSONObject.parse(params.get("data") + ""));
            String url = "";
            int methodType = 0;
            if (type == 0) {
                url = targetUrl + UrlConst.BUSI_GSAPPLIANCE.getUrl() + "?orgCode=" + orgCode;
            } else if (type == 1) {
                url = targetUrl + UrlConst.BUSI_OUTHOUSEINSTALL.getUrl() + "?orgCode=" + orgCode;
            } else if (type == 2) {
                url = targetUrl + UrlConst.BUSI_OUTHOUSEREPAIR.getUrl() + "?orgCode=" + orgCode;
            } else if (type == 3) {
                methodType = 3;
                url = targetUrl + UrlConst.QUERY_ALARMAPPLIANCE.getUrl() + param + "&orgCode=" + orgCode;
                url = url + "&openTimestamp=" + params.get("openTimestamp") + "&openSign=" + params.get("openSign");
            } else if (type == 4) {
                url = targetUrl + UrlConst.QUERY_ORDERDETAIL.getUrl() + "?orgCode=" + orgCode;
            } else if (type == 5) {
                url = targetUrl + UrlConst.BUSI_INHOUSEREPAIR.getUrl() + "?orgCode=" + orgCode;
            } else if (type == 6) {
                url = targetUrl + UrlConst.QUERY_ORGBYTYPE.getUrl() + "?orgCode=" + orgCode;
            }else if (type == 7) {
                url = targetUrl + UrlConst.BUSI_BUSIAPPLY.getUrl() + "?orgCode=" + orgCode;
            }else if (type == 8){
                url = targetUrl + UrlConst.BUSI_UNBINDALARM.getUrl() + "?orgCode=" + orgCode;
            }
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, methodType, token);
            log.info("TcisService——body,响应结果body：{}",
                    JSONObject.toJSONString(body));
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("result") + "") == 0) {
                resultMap.put("data", jsonObject.get("body"));
                resultMap.put("code", 0);
            }
            resultMap.put("msg", jsonObject.get("msg"));
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
        return resultMap;
    }

    @Override
    public void tcisRequestUnbindAlarm(UnbindAlarmRequest request,String consumerId,String spId) {
        String orgCode = companyService.getOrgCode(spId,consumerId);
        log.info("TcisService——tcisRequest,主要发送数据：{},consumerId:{}", JSONObject.toJSONString(request), consumerId);
        Map<String, Object> params = new HashMap<>();
        params.put("userid",request.getUserid());
        params.put("resid",request.getResid());
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            String url = targetUrl + UrlConst.BUSI_UNBINDALARM.getUrl() + "?orgCode=" + orgCode;
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, 0, token);
            log.info("TcisService——body,响应结果body：{}",
                    JSONObject.toJSONString(body));
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null){
                throw new BizException("设备解绑状态同步给TCIS失败");
            }
            String result = jsonObject.getString("result");
            if ( "0".equals(result) ) {
               return;
            }
            String msg = jsonObject.get("msg")!=null?jsonObject.getString("msg"):"设备解绑状态同步给TCIS失败";
            throw new BizException(msg);
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
    }

    @Override
    public void tcisRequestCancelBusiOrder(CancelBusiOrderDTO request, String consumerId, String spId) {
        String orgCode = companyService.getOrgCode(spId, consumerId);
        log.info("TcisService——tcisRequest,主要发送数据：{},consumerId:{}", JSONObject.toJSONString(request), consumerId);
        Map<String, Object> params = new HashMap<>();
        params.put("body", request);
        params.put("orgCode", orgCode);
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            String url = targetUrl + UrlConst.BUSI_CANCELBUSIORDER.getUrl() + "?orgCode=" + orgCode;
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, 0, token);
            log.info("TcisService——body,响应结果body：{}", JSONObject.toJSONString(body));
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null) {
                throw new BizException("工单取消失败");
            }
            String result = jsonObject.getString("result");
            if ("0".equals(result)) {
                return;
            }
            String msg = jsonObject.get("msg") != null ? jsonObject.getString("msg") : "工单取消同步给TCIS失败";
            throw new BizException(msg);
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
    }

    public static String openSign(Map<String, Object> map, String... keys) {
        log.info("sign map = [{}],keys = [{}]", map.toString(), keys);
        Map<String, Object> treeMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
        // 排序
        treeMap.putAll(map);
        List<String> params = new ArrayList<>(treeMap.size());
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            if ("openSign".equals(entry.getKey())) {
                continue;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(entry.getKey()).append("=");
            Object value = entry.getValue();
            if (value instanceof JSONObject) {
                sb.append(((JSONObject) value).toString(SerializerFeature.WriteMapNullValue));
            } else if (value instanceof JSONArray) {
                sb.append(((JSONArray) value).toString(SerializerFeature.WriteMapNullValue));
            } else {
                sb.append(String.valueOf(value));
            }
            params.add(sb.toString());
        }
        String signStr = Joiner.on("&").join(params);
        StringBuilder keySb = new StringBuilder();
        keySb.append(signStr);
        for (String key : keys) {
            keySb.append(key);
        }
        log.info("sb = [{}],MD5 SB=[{}]", keySb.toString(), MD5Util.encrypt(keySb.toString()).toUpperCase());
        return MD5Util.encryptUpper(keySb.toString());
    }

    public String getToken() {
        String token = "";
        Map<String, Object> params = new HashMap<>();
        params.put("openAppId", openId);
        params.put("openAppSecret", openSecret);
        try {
            String body = HttpUtil.getBody(JSONObject.toJSONString(params),
                    targetUrl + UrlConst.OPEN_TOKEN.getUrl(), "", "");
            if (StringUtils.isEmpty(body)) return null;
            log.info("getToken-response:{}", body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (Integer.parseInt(jsonObject.getString("code")) == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                token = data.getString("token");
            }
        } catch (Exception e) {
            log.error("getToken-error:{}", e);
            return null;
        }
        return token;
    }

    @Override
    public Map<String, Object> tcisRequestSmartKitchen(Map<String, Object> requestBody, int type,
                                           String param, String jvOrgCode) {
        log.info("TcisService——tcisRequest,主要发送数据：{},type：{},param:{},jvOrgCode:{}",
                JSONObject.toJSONString(requestBody), type, param,jvOrgCode);
        if (StringUtils.isEmpty(param)) param = "";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", -1);
        resultMap.put("msg", "tcis请求失败");
        JSONObject jsonObject = null;
        Map<String, Object> params = new HashMap<>();
        if (requestBody != null) {
            params = requestBody;
        }
        params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        try {
            String token = getToken();
            log.info("开放平台token：{}", token);
            if (StringUtils.isEmpty(token)) {
                throw new BizException(token + "开发平台token获取失败");
            }
            String jsonStr = openSign(params, openSecret);
            params.put("openSign", jsonStr);
            params.put("data", JSONObject.parse(params.get("data") + ""));
            String url = "";
            if (type == 2){
                url = targetUrl + UrlConst.BUSI_OUTHOUSEREPAIR.getUrl() + "?orgCode=" + jvOrgCode;
            }else if (type == 6){
                url = targetUrl + UrlConst.QUERY_ORGBYTYPE.getUrl() + "?orgCode=" + jvOrgCode;
            }
            int methodType = 0;
            //测试阶段 固定orgCode= ZB01
            log.info("TcisService——requestUrl：{}", url);
            String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", null, methodType, token);
            log.info("TcisService——body,响应结果body：{}",
                    JSONObject.toJSONString(body));
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || jsonObject.get("result") == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("result") + "") == 0) {
                resultMap.put("data", jsonObject.get("body"));
                resultMap.put("code", 0);
            }
            resultMap.put("msg", jsonObject.get("msg"));
        } catch (Exception e) {
            log.error("TcisService-error:{}", e);
            throw e;
        }
        return resultMap;
    }

}
